<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>菜单管理</span>
      </div>

      <div class="mt-2">
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="dialogTopMenuVisible = true">
          新增顶级菜单
        </el-button>
      </div>

      <!-- 树形控件 -->
      <el-tree
          ref="menuTree"
          class="menu-tree"
          :data="tableData"
          node-key="id"
          :props="defaultProps"
          :default-expanded-keys="expandedKeys"
          highlight-current
      >
        <!-- 自定义树节点内容 -->
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <i :class="data.icon" style="margin-right: 5px;"></i>
          <span>{{ data.title }}</span>
          <el-button class="btn" v-if="data.type === 1" type="text" size="mini"
                     @click="openAddSubMenuDialog(data)" style="color: #85ce61">新增</el-button>
  <el-button class="btn" type="text" size="mini" @click="openEditMenuDialog(data)">编辑</el-button>
  <el-button class="btn" type="text" size="mini" style="color: red" @click="deleteMenu(data)">删除</el-button>
        </span>
      </el-tree>

      <!-- 新增顶级菜单对话框 -->
      <el-dialog title="新增顶级菜单" :visible.sync="dialogTopMenuVisible" width="610px">
        <el-form :model="topMenuForm">
          <el-form-item label="菜单标题">
            <el-input v-model="topMenuForm.title"/>
          </el-form-item>
          <el-form-item label="图标">
            <icon-drawer v-model="topMenuForm.icon"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogTopMenuVisible = false">取消</el-button>
          <el-button type="primary" @click="addTopMenu">确定</el-button>
        </template>
      </el-dialog>

      <!-- 新增子菜单对话框 -->
      <el-dialog title="新增子菜单" :visible.sync="dialogSubMenuVisible" width="610px">
        <el-form :model="subMenuForm">
          <el-form-item label="子菜单标题">
            <el-input v-model="subMenuForm.title"/>
          </el-form-item>
          <el-form-item label="路径">
            <el-input v-model="subMenuForm.path"/>
          </el-form-item>
          <el-form-item label="图标类名">
            <icon-drawer v-model="subMenuForm.icon"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogSubMenuVisible = false">取消</el-button>
          <el-button type="primary" @click="addSubMenu">确定</el-button>
        </template>
      </el-dialog>

      <!-- 编辑菜单对话框 -->
      <el-dialog title="编辑菜单" :visible.sync="dialogEditMenuVisible" width="610px">
        <el-form :model="editMenuForm">
          <el-form-item label="菜单标题">
            <el-input v-model="editMenuForm.title"/>
          </el-form-item>
          <el-form-item label="路径" v-if="editMenuForm.type === 2">
            <el-input v-model="editMenuForm.path"/>
          </el-form-item>
          <el-form-item label="图标类名">
            <icon-drawer v-model="editMenuForm.icon"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogEditMenuVisible = false">取消</el-button>
          <el-button type="primary" @click="editMenu">保存</el-button>
        </template>
      </el-dialog>

    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request';
import IconDrawer from '@/components/IconDrawer.vue';


export default {
  components: {
    IconDrawer
  },
  name: 'MenuManagement',
  data() {
    return {
      loading: false,
      tableData: [],

      expandedKeys: [],

      // 顶级菜单弹窗控制
      dialogTopMenuVisible: false,
      topMenuForm: {
        title: '',
        icon: ''
      },

      // 子菜单弹窗控制
      dialogSubMenuVisible: false,
      subMenuForm: {
        parentId: '',
        title: '',
        icon: '',
        path: ''
      },

      dialogEditMenuVisible: false,
      editMenuForm: {
        id: '',
        title: '',
        icon: '',
        path: '',
        type: 1 // 默认
      },

      defaultProps: {
        children: 'children',
        label: 'title'
      }
    };
  },
  methods: {

    getExpandedKeys() {
      const tree = this.$refs.menuTree;
      if (!tree) return [];
      return tree.store._getAllNodes()
          .filter(node => node.expanded)
          .map(node => node.key);
    },

    handleSearch() {
      this.loading = true;
      request.get('/api/menu')
          .then(res => {
            this.tableData = res.content || [];
            this.loading = false;
          })
          .catch(err => {
            this.$message.error(err.message || '获取菜单失败');
            this.loading = false;
          });
    },

    addTopMenu() {
      const {title, icon} = this.topMenuForm;
      if (!title || !icon) {
        return this.$message.warning('请输入标题和图标');
      }

      const oldExpandedKeys = this.getExpandedKeys();

      request.post('/api/menu/top', {title, icon})
          .then(() => {
            this.$message.success('新增成功');
            this.dialogTopMenuVisible = false;
            this.topMenuForm = {title: '', icon: ''};
            this.expandedKeys = oldExpandedKeys;
            this.handleSearch();
          })
          .catch(err => {
            this.$message.error(err.message || '新增失败');
          });
    },

    openAddSubMenuDialog(parent) {
      this.subMenuForm = {
        parentId: parent.id,
        title: '',
        icon: '',
        path: ''
      };
      this.dialogSubMenuVisible = true;
    },

    addSubMenu() {
      const {parentId, title, icon, path} = this.subMenuForm;
      if (!parentId || !title || !icon || !path) {
        return this.$message.warning('请填写完整内容');
      }
      const oldExpandedKeys = this.getExpandedKeys();

      request.post('/api/menu/sub', {parentId, title, icon, path})
          .then(() => {
            this.$message.success('新增成功');
            this.dialogSubMenuVisible = false;
            this.subMenuForm = {parentId: '', title: '', icon: '', path: ''};
            this.expandedKeys = oldExpandedKeys;
            this.handleSearch();
          })
          .catch(err => {
            this.$message.error(err.message || '新增失败');
          });
    },

    openEditMenuDialog(menu) {
      this.editMenuForm = {
        id: menu.id,
        title: menu.title,
        icon: menu.icon,
        path: menu.path || '',
        type: menu.type
      };
      this.dialogEditMenuVisible = true;
    },

    editMenu() {
      const {id, title, icon, path} = this.editMenuForm;
      if (!title || !icon || (this.editMenuForm.type === 2 && !path)) {
        return this.$message.warning('请填写完整内容');
      }

      const oldExpandedKeys = this.getExpandedKeys();

      request.post('/api/menu/edit', {id, title, icon, path})
          .then(() => {
            this.$message.success('编辑成功');
            this.dialogEditMenuVisible = false;
            this.expandedKeys = oldExpandedKeys;
            this.handleSearch();
          })
          .catch(err => {
            this.$message.error(err.message || '编辑失败');
          });
    },

    deleteMenu(menu) {
      const oldExpandedKeys = this.getExpandedKeys();
      this.$confirm(`确定要删除菜单「${menu.title}」吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        request.post('/api/menu/delete', {id: menu.id})
            .then(() => {
              this.$message.success('删除成功');
              this.expandedKeys = oldExpandedKeys;
              this.handleSearch();
            })
            .catch(err => {
              this.$message.error(err.message || '删除失败');
            });
      }).catch(() => {
      });
    }

  },
  mounted() {
    this.handleSearch();
  }
};
</script>

<style scoped>
.menu-tree {
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 5px;
}

.custom-tree-node {
  width: 100%;
}

.menu-path {
  color: #999;
  font-size: 12px;
  margin-left: 8px;
}

.mt-2 {
  margin-top: 20px;
  margin-bottom: 20px;
}

.btn {
  margin-left: 25px;
}

</style>
